using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityHelpers;

namespace Game.UI
{
    /**
        
     */
    public class ToastManager : SingletonBehaviour<ToastManager>
    {
        [SerializeField]
        private GameObject toastPrefab;

        [SerializeField]
        private Transform toastContainer;

        [SerializeField]
        private float toastOffset = -40f;
        private Queue<Toast> _toastQueue = new Queue<Toast>();
        private Queue<Toast> _pool = new Queue<Toast>();

        private void SetToastPosition(Toast toast, ToastPosition position)
        {
            toast.SetPosition(position);

            // 根据position设置toast的位置，取对应的子物体
            // toast.transform.position = toastContainer.GetChild((int)position).position;
            toast.transform.SetParent(toastContainer.GetChild((int)position));
        }

        public void ShowToast(string text, ToastPosition position = ToastPosition.Bottom)
        {
            if (!_pool.TryDequeue(out Toast toast))
            {
                toast = Instantiate(toastPrefab, toastContainer).GetComponent<Toast>();
            }

            SetToastPosition(toast, position);
            toast.SetText(text);
            toast.Show();
            // 启动协程，等待时间结束
            StartCoroutine(HideToast(toast));
            _toastQueue.Enqueue(toast);

            // 如果队列中的最后一个还处于显示状态，则往下偏移一个位置，避免重叠
            if (_toastQueue.Count > 1)
            {
                Toast lastToast = _toastQueue.Peek();
                if (lastToast.State == Toast.ToastState.Showing)
                {
                    lastToast.transform.position += new Vector3(0, toastOffset, 0);
                }
            }
        }

        private IEnumerator HideToast(Toast toast)
        {
            yield return new WaitUntil(() => toast.State == Toast.ToastState.Hidden);
            toast.Hide();
            _pool.Enqueue(toast);
            _toastQueue.Dequeue();
        }
    }
}